var canvas = document.getElementsByTagName('canvas')[0];
/* canvas.width = 1000;
canvas.height = 1000; */

var ctx = canvas.getContext('2d');//ctx就是画笔
function random(x,y){
    return Math.floor(Math.random()*(y-x+1))+x;
}
var w = canvas.width;
var h = canvas.height;

function Ball(){
    //半径 x y x轴上的速度 运动方向
    this.right = true;
    this.bottom = true;
    this.r = random(5,6);
    this.x = random(this.r,w-this.r);
    this.y = random(this.r,h-this.r);
    this.stepX = random(6,9);
    this.stepY = random(2,5);
    this.color = "rgb("+random(0,255)+","+random(0,255)+","+random(0,255)+")"
}

Ball.prototype.move = function(){
    /* if(this.x <= this.r){
        this.x += this.stepX;
    }else{
        this.x -= this.stepX;
    } */

    if(this.right){
        this.x += this.stepX;
        if(this.x >= w - this.r){
            this.right = false;
        }
    }else{
        this.x -= this.stepX;
        if(this.x <= this.r){
            this.right = true;
        }
    }


    if(this.bottom){
        this.y += this.stepY;
        if(this.y >= h - this.r){
            this.bottom = false;
        }
    }else{
        this.y -= this.stepY;
        if(this.y <= this.r){
            this.bottom = true;
        }
    }


    ctx.beginPath();
    ctx.fillStyle = this.color;
    ctx.arc(this.x,this.y,this.r,0,2*Math.PI);
    ctx.fill();
    ctx.closePath()
}

// var b = new Ball();
var balls = [];
for(var i = 0;i<400;i++){
    balls.push(new Ball());
}
// console.log(balls);
setInterval(function(){
    ctx.clearRect(0,0,w,h);
    for(var i = 0;i<balls.length;i++){
        balls[i].move();
    }
},16)